import { defineStore } from 'pinia'
import { ref } from 'vue'
import { dynamicMenuAPI } from '@/api'
import type { DynamicMenu } from '@/types'
import { useAuthStore } from './auth'

export const useMenuStore = defineStore('menu', () => {
  // State
  const dynamicMenus = ref<DynamicMenu[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  // Actions
  const loadDynamicMenus = async () => {
    loading.value = true
    error.value = null
    
    try {
      const response = await dynamicMenuAPI.getMenus()
      if (response.success) {
        dynamicMenus.value = response.data || []
      } else {
        error.value = response.message || '获取动态菜单失败'
      }
    } catch (err) {
      console.error('加载动态菜单失败:', err)
      error.value = '网络错误，请稍后重试'
    } finally {
      loading.value = false
    }
  }

  const createMenu = async (menuData: {
    name: string
    key: string
    icon?: string
    table_name: string
    description?: string
    permissions?: string[]
    columns_config?: any
    sort_order?: number
  }) => {
    try {
      const response = await dynamicMenuAPI.createMenu(menuData)
      if (response.success) {
        // 重新加载菜单列表
        await loadDynamicMenus()
        return response.data
      } else {
        throw new Error(response.message || '创建菜单失败')
      }
    } catch (err) {
      console.error('创建菜单失败:', err)
      throw err
    }
  }

  const updateMenu = async (id: number, menuData: Partial<DynamicMenu>) => {
    try {
      const response = await dynamicMenuAPI.updateMenu(id, menuData)
      if (response.success) {
        // 重新加载菜单列表
        await loadDynamicMenus()
        return response.data
      } else {
        throw new Error(response.message || '更新菜单失败')
      }
    } catch (err) {
      console.error('更新菜单失败:', err)
      throw err
    }
  }

  const deleteMenu = async (id: number) => {
    try {
      const response = await dynamicMenuAPI.deleteMenu(id)
      if (response.success) {
        // 重新加载菜单列表
        await loadDynamicMenus()
      } else {
        throw new Error(response.message || '删除菜单失败')
      }
    } catch (err) {
      console.error('删除菜单失败:', err)
      throw err
    }
  }

  // Getters
  const getVisibleMenus = () => {
    const authStore = useAuthStore()
    
    return dynamicMenus.value.filter(menu => {
      // 检查菜单状态
      if (menu.status !== 'active') return false
      
      // 检查用户权限
      if (menu.permissions && menu.permissions.length > 0) {
        // 检查用户是否拥有菜单所需的任一权限
        return authStore.hasAnyPermission(menu.permissions)
      }
      
      // 如果没有设置权限要求，则显示
      return true
    }).sort((a, b) => {
      // 按排序顺序和创建时间排序
      if (a.sort_order !== b.sort_order) {
        return a.sort_order - b.sort_order
      }
      return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
    })
  }

  const getMenuByKey = (key: string) => {
    return dynamicMenus.value.find(menu => menu.key === key)
  }

  const getMenuByTableName = (tableName: string) => {
    return dynamicMenus.value.find(menu => menu.table_name === tableName)
  }

  // AI菜单控制已集成到聊天中，通过SQL直接执行，无需单独API

  // Initialize
  const initialize = async () => {
    const authStore = useAuthStore()
    
    // 只有在用户已认证的情况下才加载动态菜单
    if (authStore.isAuthenticated) {
      try {
        await loadDynamicMenus()
      } catch (error) {
        console.warn('初始化动态菜单失败，将跳过:', error)
        // 不抛出错误，避免阻断应用初始化
      }
    }
  }

  return {
    // State
    dynamicMenus,
    loading,
    error,
    
    // Actions
    loadDynamicMenus,
    createMenu,
    updateMenu,
    deleteMenu,
    initialize,
    
    // Getters
    getVisibleMenus,
    getMenuByKey,
    getMenuByTableName
  }
})
